package edu.henu.personnel.controller;

import edu.henu.personnel.entity.Catalog;
import edu.henu.personnel.service.catalog.CatalogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: PersonnelProject
 * @description: 二级目录控制器
 * @author: zhuyang
 * @create: 2019-05-16 13:27
 */

@Slf4j
@Controller
public class CatalogController {

    @Autowired
    private CatalogService catalogService;

    @GetMapping("/catalogs")
    public String list(Model model) {
        List<Catalog> catalogList = catalogService.getAllCatalogInfo();
        List<Catalog> catalogs = new ArrayList<>();

        for (Catalog catalog : catalogList) {
            if (!(catalog.getCmemo().equals("下载中心") || (catalog.getCname().equals("人才队伍")))) {
                catalogs.add(catalog);
            }
        }
        model.addAttribute("catalogList", catalogs);
        return "catalog/list";
    }

    @GetMapping("catalog")
    public String toAddPage() {
        return "catalog/add";
    }

    @PostMapping("/catalog")
    public String addCatalog(Catalog catalog, Model model) {
        int result = catalogService.addCatalogInfo(catalog);
        model.addAttribute("addCatalogResult", result);
        return "redirect:/catalogs";
    }

    @GetMapping("/catalog/{cid}")
    public String toEditPage(@PathVariable Integer cid, Model model) {
        Catalog catalog = catalogService.getCatalogInfoById(cid);
        model.addAttribute("catalog", catalog);
        return "catalog/modify";
    }

    @PutMapping("/catalog")
    public String modifyCatalog(Catalog catalog, Model model) {
        int result = catalogService.modifyCatalogInfo(catalog);
        model.addAttribute("modifyCatalogResult", result);
        return "redirect:/catalogs";
    }

    @DeleteMapping("/catalog/{cid}")
    public String deleteCatalog(@PathVariable Integer cid, Model model) {
        int result = catalogService.removeCatalogInfo(cid);
        model.addAttribute("removeCatalogResult", result);
        return "redirect:/catalogs";
    }

}
